|
|
|
|
|
|
|
To make Visual Basic programs truly functional, they must be able to store information temporarily. With Visual Basic, as with any programming language, there is a need to remember information as the program runs. Visual Basic allows you to store information using variables and constants. |
|
|
|
|
|
|
|
|
This chapter examines the types of variables and constants available to Visual Basic programmers and explores how to use them to allow the necessary retention of information. |
|
|
|
|
|
|
|
|
Introduction to Variables |
|
|
|
|
|
|
|
|
Simply stated, you use variables to store information in the computer's memory while your programs are running. Three components define a variable: |
|
|
|
|
|
|
|
|
The variable's name (which correlates to its location in memory) |
|
|
|
|
|
|
|
|
The type of information being stored |
|
|
|
|
|
|
|
|
The actual information itself |
|
|
|
|
|
|
|
|
Suppose you are given this assignment: "Go count all the cars in the parking lot." As you count each car, you are storing information in a variable. Your location in memory is either a notepad or your brain. The type of information being stored is a number. And the actual information you are storing is the current number of cars. |
|
|
|
|
|
|
|
|
As the name variable suggests, the information stored in a variable can change (vary) over time. In the example of counting cars, the count will be increased periodically. With any variable, there are two basic functions you can perform: storing information (writing on the notepad) and retrieving information (reading what is written on the notepad). |
|
|
|
|
|
|
|
|
A variable must have a name for you to be able to assign values to it. You might have noticed statements like the following in earlier examples: |
|
|
|
|
|
|
|
|
This example illustrates a Dim, or Dimension, statement, used for dimensioning (or declaring) variables (see the section "Variable Declarations" later in this chapter). When your program declares a variable, it is, in essence, telling Visual Basic, "Set aside a memory location that will be used to store variable information; call it X." The last two words in the Dim statement tell Visual Basic what type of information you plan to storein this case, integer numbers. This information helps determine how much memory is to be set aside for the variable. |
|
|
|
|
|
|
|
|
In naming a variable, you have a tremendous amount of flexibility. Variable names can be simple, or they can be descriptive of the information they contain. In the preceding example, X is a perfectly legal name but not very descriptive to the readers. Although you are allowed great latitude in naming variables, you must adhere to a few restrictions: |
|
|
|
|
|
|
|
|
The name must start with a letter, not a number or other character. |
|
|
|
|
|